package logic

import (
	"context"
	"errors"
	"smsbridge/models/cache"
	"smsbridge/models/mysql"
	"smsbridge/pkg"
	"smsbridge/smsrpc/internal/svc"
	"smsbridge/smsrpc/smsrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *smsrpc.LoginRequest) (*smsrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindName(mysql.DB, in.Username); err != nil {
		return nil, errors.New("用户名不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "login"+in.Password).Int()
	if result >= 3 {
		return nil, errors.New("密码错误三次不允许登录")
	}

	if user.Password != pkg.Md5(in.Password) {
		cache.Rdb.Incr(l.ctx, "login"+in.Password)
		if result == 2 {
			cache.Rdb.Set(l.ctx, "login"+in.Password, 3, time.Minute*1)
			return nil, errors.New("密码错误三次封禁1分钟")
		}
		return nil, errors.New("密码错误")
	}
	i1, _ := cache.Rdb.Get(l.ctx, "smsTwo"+in.Username).Result()
	if i1 != in.Sms {
		return nil, errors.New("短信验证码错误")
	}
	i2, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Result()
	if i2 != in.Captcha {
		return nil, errors.New("图形验证码错误")
	}
	cache.Rdb.Del(l.ctx, "smsTwo"+in.Username)
	cache.Rdb.Del(l.ctx, "captcha"+in.Username)
	return &smsrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
